package com.defysoft.waukids.slide;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity_UpPhoto;
import com.defysoft.waukids.Custom_Data_Type.MAIN_SLIDE_CHILDREN_LOAD;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.PublicSharedpreferences.SF_Student_Key;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Main_Slide_Children extends BaseActivity_UpPhoto implements OnClickListener{
	View spinnerView;
	Toolbar toolbar;
	ImageView imageView;
	EditText editText[] = new EditText[5];
	TextView title, studentName;
	String schoolName, className, beaconId,newPhoto, memberPhone, memberEmail;
	MAIN_SLIDE_CHILDREN_LOAD mainChildrenLoad;
	//이미지업로드
	DisplayImageOptions options; 
	ImageLoader imageLoader;
	
	//수정완료 후 어린이사진, 맴버이름 쉐어프리퍼런스 바꾸기.
	PublicSharedpreferences psf;
	SharedPreferences.Editor editor;
	Data_Sharedpreferences.SF_Member member;
	Data_Sharedpreferences.SF_Student student;

	public Sqlite_Connect sqlite_Connect;
	
	private final int FIRST_THREAD = 1;
	private final int SUCCESS_FIRST = 9;
	private final int FAIR_FIRST = 10;
	
	private final int PHOTOUP_THREAD = 3;
	private final int SUCCESS_PHOTO = 5;
	private final int FAIR_PHOTO = 6;

	private final int EDIT_THREAD = 2;
	private final int SUCCESS_EDIT = 7;
	private final int FAIR_EDIT = 8;

	private final int NOCHANGE_PHOTO = 11;
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.main_slide_children_activity);
		setToolbar();
		setImgSetting();
		setStartData();
		startNetwork(FIRST_THREAD);
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}
	
	private void setToolbar() {
		spinnerView = findViewById(R.id.MAIN_SLIDE_CHILDREN_TOOLBAR_VIEW);
		spinnerView.setOnClickListener(this);
		toolbar = (Toolbar)findViewById(R.id.MAIN_SLIDE_CHILDREN_TOOLBAR);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		psf.setStudentsp();
		member = psf.getMembersp();
		student = psf.getStudentsp();
		
		imageView = (ImageView)findViewById(R.id.MAIN_SLIDE_CHILDREN_IMG);
		addImageData(imageView);
		studentName = (TextView)findViewById(R.id.MAIN_SLIDE_CHILDREN_STUDENT_NAME);
		editText[0] = (EditText)findViewById(R.id.MAIN_SLIDE_CHILDREN_SCHOOL_NAME);
		editText[1] = (EditText)findViewById(R.id.MAIN_SLIDE_CHILDREN_CLASS_NAME);
		editText[2] = (EditText)findViewById(R.id.MAIN_SLIDE_CHILDREN_BEACON);
		editText[3] = (EditText)findViewById(R.id.MAIN_SLIDE_CHILDREN_MEMBER_PHONE);
		editText[4] = (EditText)findViewById(R.id.MAIN_SLIDE_CHILDREN_MEMBER_EMAIL);
		
		
		//이미지 터치시 동작
		imageList.get(0).iv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
					addPhotoListener(0, 1, 1, 120, 120);
			}
		});
		
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS_FIRST:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			String Bea_Id="";
			
			//비콘자르기.
			try{
				Bea_Id = mainChildrenLoad.beaconid.split(":")[3]+""+mainChildrenLoad.beaconid.split(":")[4]+""+mainChildrenLoad.beaconid.split(":")[5];
			}catch(Exception ex){
				Bea_Id = "비콘이 없습니다.";
			}
			
			studentName.setText(mainChildrenLoad.Stu_Name);
			editText[0].setText(mainChildrenLoad.schoolname);
			editText[1].setText(mainChildrenLoad.classname);
			editText[2].setText(Bea_Id);
			editText[3].setText(mainChildrenLoad.Mem_Phone);
			editText[4].setText(member.Email);
			//이미지 유무
			if (mainChildrenLoad.Stu_Photo.length() > 5) {
				imageLoader.displayImage(PublicConstant.HTTP_URL_STUDENTPHOTO+mainChildrenLoad.Stu_Photo,  imageView, options, null);
			}
			
			break;
		case FAIR_FIRST:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}		
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();			
			break;
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}	
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_Slide_Children", member.Email);
			break;
			
		case SUCCESS_PHOTO:
			endDIal();			
			if (upThread != null) {upThread.interrupt();}
			Toast.makeText(this, "사진올리기가 완료되었습니다. 잠시만 기다려 주세요.", Toast.LENGTH_SHORT).show();
			newPhoto = (String)_message.obj;
			startNetwork(EDIT_THREAD);
			break;
			
		case FAIR_PHOTO:
			endDIal();			
			if (upThread != null) {upThread.interrupt();}
			Toast.makeText(this,(String)_message.obj, Toast.LENGTH_SHORT).show();			
			break;
		case SUCCESS_EDIT:		//수정 성공.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, (String)_message.obj, Toast.LENGTH_SHORT).show();		
			//쉐어드프리퍼런스 바꾸기.
			editor = psf.getStudent_edit();
			editor.putString(SF_Student_Key.PHOTO, newPhoto);
			editor.commit();
			setResult(REFRESH_CODE);
			finish();
			break;
		case FAIR_EDIT:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}		
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();			
			break;
		case NOCHANGE_PHOTO:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}	
			finish();
			break;
		}
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case FIRST_THREAD:
					firstThread();
					break;
				case PHOTOUP_THREAD:
					upImageThread(0);
					break;
				case EDIT_THREAD:
					editThread();
					break;
				}
			}
		});
		startDIal();	
		firstThread.start();
	}
	
	protected void firstThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code="+ CODE_MAIN_SLIDE_CHILDREN_LOAD 
					+"&PK_Mem_Email="+ member.Email+"&connect="+member.Connect ));
			if (jsonObject.getBoolean("success")) {
				mainChildrenLoad = JsonParser.Main_Slide_Children_Load(jsonObject.getString("payload"));
				onNetworkCallback(SUCCESS_FIRST, "");
			} else {
				onNetworkCallback(FAIR_FIRST, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where firstThread()");
		}		
	}
	/** 사진 올리기 후 DB입력 스레드 */
	protected void editThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code="+ CODE_MAIN_SLIDE_CHILDREN_CHANGE +
					"&email="+ member.Email
					+"&photo="+newPhoto+"&connect="+member.Connect));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_EDIT, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIR_EDIT, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where editThread()");
		}			
	}
	/** 사진올리기 스레드 */
	@Override
	public void upImageThread(int choice) {
		// TODO Auto-generated method stub
		super.upImageThread(choice);
		final int cho = choice;
		upThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				JSONObject jsonObject = null;
				try {
					if (imageList.get(cho).bitmap != null) {
						StringBuffer postDataBuilder = new StringBuffer();
						// 추가하고 싶은 Key & Value 추가key & value를 추가한 후 꼭 경계선을 삽입해줘야
						// 데이터를 구분할 수 있다.파일 첨부
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setValue("filename", "student"));
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setValue("folder", "studentphoto"));
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setValue("delimg", mainChildrenLoad.Stu_Photo));
						postDataBuilder.append(delimiter);
						postDataBuilder.append(setFile("photo", "temp.jpg"));
						postDataBuilder.append("\r\n");
						// 커넥션 생성 및 설정
						HttpURLConnection conn = (HttpURLConnection) new URL(
								HTTP_URL_PHOTOUP)
								.openConnection();
						conn.setDoInput(true);
						conn.setDoOutput(true);
						conn.setUseCaches(false);
						conn.setRequestMethod("POST");
						conn.setRequestProperty("Connection", "Keep-Alive");
						conn.setRequestProperty("Content-Type",
								"multipart/form-data;boundary=" + boundary);// 전송 작업 시작
						DataOutputStream out = new DataOutputStream(
								new BufferedOutputStream(conn.getOutputStream()));
						// 위에서 작성한 메타데이터를 먼저 전송한다. (한글이 포함되어 있으므로 UTF-8 메소드사용)
						out.writeUTF(postDataBuilder.toString());
						// 파일 복사 작업 시작
						byte[] buffer = getbitmap(imageList.get(cho).bitmap,
								70);

						// 버퍼 크기만큼 파일로부터 바이트 데이터를 읽는다.전송
						out.write(buffer);
						out.writeBytes(delimiter); // 반드시 작성해야 한다.
						out.flush();
						out.close();
						// 전송끝, 피드백
						BufferedReader br = new BufferedReader(
								new InputStreamReader(conn.getInputStream()));
						String checkmsg;
						String msg = br.readLine();
						while ((checkmsg = br.readLine()) != null) {
							msg += checkmsg;
						}
						jsonObject = new JSONObject(msg);
						if (jsonObject.getString("success").equals("true")) {
							onNetworkCallback(SUCCESS_PHOTO,  jsonObject.getString("payload"));
							// 성공처리
						} else {
							onNetworkCallback(FAIR_PHOTO,  jsonObject.getString("message"));
							// 실패처리
						}
					} else {	//사진을 안바꾸고 눌림.
						onNetworkCallback(NOCHANGE_PHOTO, "");						
					}
				} catch (Exception e) {
					onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where upImageThread(int choice)");
				}
			}
			
		});
		upThread.start();
	}
	
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		/*case R.id.MAIN_SLIDE_CHILDREN_IMG:	//사진 클릭
				startupNetwork(PHOTOUP_THREAD);
			break;*/
		case R.id.MAIN_SLIDE_CHILDREN_TOOLBAR_VIEW:	//완료버튼 클릭
					alertDialog("정보를 변경 하겠습니까?", PHOTOUP_THREAD);

			break;

		}
	}
	

	public void setImgSetting() {
		// 이미지 세팅.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
		/* .imageScaleType(ImageScaleType.EXACTLY) */
		.cacheOnDisc(true).considerExifParams(true).build();
	}
	
	// 네.아니오.선택다이얼로그
	void alertDialog(String string_title, int int_code) {
		final String title = string_title;
		final int code = int_code;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Main_Slide_Children.this);
		AlertDialog alert;
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						startNetwork(code);
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}
	
	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
			TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(Main_Slide_Children.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
		}
	};
}
